import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
axios.defaults.withCredentials=true //让ajax携带cookie
// 创建 axios 实例
const http = axios.create({
    timeout: 60000,
    // withCredentials: true
});
// eslint-disable-next-line no-unused-vars
// 设置 post、put 默认 Content-Type
http.defaults.headers.post["Content-Type"] = "application/json";
http.defaults.headers.put["Content-Type"] = "application/json";
// 添加请求拦截器
http.interceptors.request.use(
    (config) => {
        if (config.method === "post" || config.method === "put") {
            // post、put 提交时，将对象转换为string, 为处理Java后台解析问题
            config.headers["Content-Type"] = "application/json";
        }
        // 请求发送前进行处理
        return config;
    },
    (error) => {
        // 请求错误处理
        return Promise.reject(error);
    }
);

// 添加响应拦截器
http.interceptors.response.use(
    (response) => {
        if (response.status == 200) {
            if (response.data.code == 401) {
                ElMessage.error("Login is invaild, Please login again!");
                setTimeout(() => {
                    router.push("/");
                }, 1000);
            } else {
                return response
            }
        }
        return response
    },
    (error) => {
        console.log(error);
        let info = {};
        const data = error.response;
        if (!error.response) {
            info = {
                code: 5000,
                msg: "Network Error",
            };
        } else {
            // 此处整理错误信息格式
            info = {
                code: data?.status,
                data: data?.data,
                msg: data?.statusText,
            };
        }
        return Promise.reject(info.msg);
    }
);

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function () {
    return http;
}
